//user模块的小仓库
//引入接口文件
import { reqSendCode, resRegister, resLogin, reqUserInfo, reqLogout } from '@/api'
const state = {
    code: '',
    token: localStorage.getItem('TOKEN'),
    userInfo: {}
};
const actions = {
    //通过api里的接口函数调用，向服务器发请求，获取服务器的数据
    //获取验证码
    async sendCode({ commit }, phone) {
        let res = await reqSendCode(phone);
        if (res.code == 200) {
            commit('SENDCODE', res.data)
        } else {
            return Promise.reject(new Error(res.message))
        }
    },
    //提交注册
    async register({ commit }, user) {
        let res = await resRegister(user);
        if (res.code == 200) {
            return 'register success'
        } else {
            return Promise.reject(new Error(res.message))
        }
    },
    //登录
    async login({ commit }, user) {
        let res = await resLogin(user);
        if (res.code == 200) {
            commit('LOGIN', res.data.token);
            //持久化存储token
            localStorage.setItem('TOKEN', res.data.token)
        } else {
            return Promise.reject(new Error(res.message))
        }
    },
    //获取用户信息
    async userInfo({ commit }) {
        let res = await reqUserInfo();
        if (res.code == 200) {
            commit('USERINFO', res.data)
        } else {
            return Promise.reject(new Error(res.message))
        }
    },
    //退出登录
    async logout({ commit }) {
        let res = await reqLogout();
        if (res.code == 200) {
            commit("LOGOUT");
        } else {
            return Promise.reject(new Error(res.message))
        }
    }
};
const mutations = {
    SENDCODE(state, code) {
        state.code = code
    },
    LOGIN(state, token) {
        state.token = token
    },
    USERINFO(state, userInfo) {
        state.userInfo = userInfo
    },
    LOGOUT(state) {
        state.token = '';
        state.userInfo = {};
        localStorage.removeItem('TOKEN')
    }
};

const getters = {

};

export default {
    state,
    mutations,
    actions,
    getters
}